package com.canbot.u05.utils;


import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.MainApplication;
import com.canbot.u05.socket.IpMsgConst;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by X230 on 2017/7/3.
 */

public class ExcelKqDownLoadLoader extends AsyncTask<String, Void, String> {

        private Context context;

        private OkHttpClient mClient;

        public ExcelKqDownLoadLoader(Context context) {

                this.context = context;
                mClient = new OkHttpClient();

        }

        @Override
        protected String doInBackground(String... params) {

                Logger.e("AttendanceStatisticsActivity", "参数=" + params[0]);

                List<String> monthList = JSON.parseArray(params[0], String.class);
                if (monthList != null && monthList.size() != 0) {
                        for (String s : monthList) {
                                downLoad(s);
                        }
                        LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(ConstUtils.ACTION_KQ_DOWNLOAD_SUCCESS));
                        MainApplication.getInstance().downLoadSuccess = true;
                }
                return null;
        }

        private void downLoad(final String month) {
                final String dirPath = ConstUtils.PATH_SD + "/kq";
                final File file = new File(dirPath, month + ".xls");

                if (file.exists()) {
                        file.delete();
                        Logger.e("AttendanceStatisticsActivity","删除文件"+file.getName());
                }else {
                        try {
                                file.createNewFile();
                        }
                        catch (IOException e) {
                                e.printStackTrace();
                        }
                }
                Request request = new Request.Builder().url("http://" + IpMsgConst.SOCKET_HOST2 + ":7755/kq/" + month + ".xls").build();
                Call call = mClient.newBuilder().writeTimeout(500, TimeUnit.SECONDS).connectTimeout(500, TimeUnit.SECONDS).readTimeout(500, TimeUnit.SECONDS).build().newCall(request);
//                Logger.e("AttendanceStatisticsActivity","地址= " + "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/kq/" + month + ".xls");

                call.enqueue(new Callback() {

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {

//                                Logger.e("AttendanceStatisticsActivity","response = "+ response.body().toString());
                                InputStream is = null;
                                byte[] buf = new byte[2048];
                                int len = 0;

                                FileOutputStream fos = null;
                                try {

                                        File dir = new File(dirPath);
                                        if (!dir.exists()) {
                                                dir.mkdirs();
                                        }
                                        is = response.body().byteStream();
                                        long total = response.body().contentLength();
                                        Logger.e("AttendanceStatisticsActivity", "total大小 = " + total);
                                        File file = new File(dirPath, month + ".xls");

                                        if (file.exists()) {
                                                file.delete();
                                        }
                                        fos = new FileOutputStream(file);
                                        long sum = 0;
                                        while ((len = is.read(buf)) != -1) {
                                                fos.write(buf, 0, len);
                                                sum += len;
//                                                Logger.e("AttendanceStatisticsActivity","大小 = "+ sum);
                                        }
                                        fos.flush();
                                }
                                catch (IOException e) {

                                }
                                finally {
                                        Logger.e("AttendanceStatisticsActivity", "完成 ");
                                        if (is != null) {
                                                is.close();
                                        }
                                        if (fos != null) {
                                                fos.close();
                                        }
                                }
                        }

                        @Override
                        public void onFailure(Call call, IOException e) {
                                Logger.e("AttendanceStatisticsActivity", "失败 " + e.toString());
                        }
                });
        }


}
